////
//// Created by xuyang on 2019/1/12.
////
//
//#include <sys/socket.h>
//#include <sys/un.h>
//#include <string.h>
//#include <stdio.h>
//#include <errno.h>
//#include <unistd.h>
//
//#define SOCKET_NAME "/tmp/connection-uds-fd"
//
//void send_fd(int fd){
//    struct msghdr msg;
//    struct cmsghdr *cmsg=NULL;
//    int io[3]={0,1,2};
//    char buf[CMSG_SPACE(sizeof(io))];
//    struct iovec iov;
//    memset(&msg,0, sizeof(struct msghdr));
//    iov.iov_len=1;
//    int dummy;
//    iov.iov_base=&dummy;
//
//    msg.msg_iov=&iov;
//    msg.msg_iovlen=1;
//    msg.msg_control=buf;
//    msg.msg_controllen= sizeof(buf);
//
//    cmsg=CMSG_FIRSTHDR(&msg);
//    cmsg->cmsg_len=CMSG_LEN(sizeof(io));
//    cmsg->cmsg_level=SOL_SOCKET;
//    cmsg->cmsg_type=SCM_RIGHTS;
//
//    memcpy(CMSG_DATA(cmsg),io, sizeof(io));
//
//    msg.msg_controllen=cmsg->cmsg_len;
//
//    int size=sendmsg(fd,&msg,0);
//
//}
//
//int main(){
//    int fd;
//    int socket_fd;
//    struct sockaddr_un sun;
//    socket_fd=socket(PF_UNIX,SOCK_STREAM,0);
//    sun.sun_family=AF_UNIX;
//    strncpy(sun.sun_path,SOCKET_NAME, sizeof(sun.sun_path)-1);
//    bind(socket_fd,(struct sockaddr*)&sun, sizeof(sun));
//    listen(socket_fd,10);
//    fd=accept(socket_fd,NULL,NULL);
//    send_fd(fd);
//    return 0;
//}



#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>

#define SOCKET_NAME "/tmp/connection-uds-fd"

int make_connection()
{
    int fd;
    int connection_fd;
    int result;
    struct sockaddr_un sun;

    fd = socket(PF_UNIX, SOCK_STREAM, 0);

    sun.sun_family = AF_UNIX;
    strncpy(sun.sun_path, SOCKET_NAME, sizeof(sun.sun_path) - 1);

    result = bind(fd, (struct sockaddr*) &sun, sizeof(sun));
    listen(fd, 10);
    connection_fd = accept(fd, NULL, NULL);

    return connection_fd;
}

void send_fds(int socket_fd)
{
    struct msghdr msg;
    struct cmsghdr *cmsg = NULL;
    int io[3] = { 0, 1, 2 };
    char buf[CMSG_SPACE(sizeof(io))];
    struct iovec iov;
    int dummy;

    memset(&msg, 0, sizeof(struct msghdr));

    iov.iov_base = &dummy;
    iov.iov_len = 1;

    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = buf;
    msg.msg_controllen = sizeof(buf);

    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_len = CMSG_LEN(sizeof(io));
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;

    memcpy(CMSG_DATA(cmsg), io, sizeof(io));

    msg.msg_controllen = cmsg->cmsg_len;

    int size;
    size = sendmsg(socket_fd, &msg, 0);
    // printf("%d %d\n", size, errno);
}

int main(int argc, char const *argv[])
{
    int connection_fd;

    printf("write from outlet\n");
    connection_fd = make_connection();
    send_fds(connection_fd);

    while(1) {
        sleep(1);
    }

    return 0;
}